﻿using System;
using System.Windows.Forms;
using VMWorkshop.Domain;
using VMWorkshop.WinForms.Models.ViewModels;

namespace VMWorkshop.WinForms.Views
{
    public partial class Demo : Form
    {
        private DemoViewModel _vm;

        public Demo()
        {
            InitializeComponent();
            this.Load += new EventHandler(Demo_Load);
        }

        void Demo_Load(object sender, EventArgs e)
        {
            this._vm = new DemoViewModel(new ProductRepository());
            this.InitializeProductsGrid();
            this.UpdateView();
        }

        private void InitializeProductsGrid()
        {
            this.productsGrid.AutoGenerateColumns = false;
            this.productsGrid.DataSource = this._vm.Products;
            this.productsGrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            this.productsGrid.ClearSelection();
        }

        private void UpdateView()
        {
            this.editPanel.Visible = this._vm.IsEditFormVisible;
            this.updateMsgPanel.Visible = this._vm.IsUpdateMessageVisible;

            this.txtDescription.Text = this._vm.SelectedProduct.Description;
            this.txtPrice.Text = this._vm.SelectedProduct.Price;
            this.txtQuantity.Text = this._vm.SelectedProduct.QuantityOnHand;
            this.txtReleaseDate.Text = this._vm.SelectedProduct.ReleaseDate;
            this.txtTitle.Text = this._vm.SelectedProduct.Title;
        }

        private void UpdateModel()
        {
            this._vm.SelectedProduct.Description = this.txtDescription.Text;
            this._vm.SelectedProduct.Price = this.txtPrice.Text;
            this._vm.SelectedProduct.QuantityOnHand = this.txtQuantity.Text;
            this._vm.SelectedProduct.ReleaseDate = this.txtReleaseDate.Text;
            this._vm.SelectedProduct.Title = this.txtTitle.Text;
        }

        private void productsGrid_SelectionChanged(object sender, EventArgs e)
        {
            if (this.productsGrid.SelectedRows.Count > 0)
            {
                string id = this.productsGrid.SelectedRows[0].Cells["ProductId"].Value.ToString();
                this._vm.GetSelectedProduct(id);
                this.UpdateView();   
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            this.UpdateModel();
            this._vm.Persist();
            this.UpdateView();
        }
    }
}
